package 二级缓存;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/8/15 16:45
 * @description:
 * @version:
 */
public class SecondLevelCache implements Cache{
    private Cache firstLevelCache;
    private Cache persistentCache;
    private int maxCapacity;

    public SecondLevelCache(Cache firstLevelCache, Cache persistentCache, int maxCapacity) {
        this.firstLevelCache = firstLevelCache;
        this.persistentCache = persistentCache;
        this.maxCapacity = maxCapacity;
    }

    @Override
    public Object get(String key) {
        Object value = firstLevelCache.get(key);
        if (value == null) {
            value = persistentCache.get(key);
            if (value != null) {
                firstLevelCache.put(key, value, Long.MAX_VALUE); // 永不过期
            }
        }
        return value;
    }

    @Override
    public void put(String key, Object value, long expirationTime) {
        firstLevelCache.put(key, value, expirationTime);
        persistentCache.put(key, value, expirationTime);
    }

    @Override
    public void remove(String key) {
        firstLevelCache.remove(key);
        persistentCache.remove(key);
    }

    @Override
    public void clear() {
        firstLevelCache.clear();
        persistentCache.clear();
    }

    @Override
    public void removeExpired() {
        firstLevelCache.removeExpired();
        persistentCache.removeExpired();
    }
}
